from flask import Blueprint, request, jsonify, current_app, g

from app.src.auth import auth_bp
from app.src.auth.services import AuthService
from flask import redirect

# @auth_bp.before_request
# def check_auth():
#     from app.src.auth.services import AuthService
#     # 跳过不需要验证的路由
#     # 跳过不需要验证的路由
#     if request.endpoint and request.endpoint.endswith('login'):
#         return

#     token = request.headers.get('Authorization')
#     if not token:
#         return jsonify({
#             'code': 401,
#             'message': '未提供认证token'
#         }), 401

#     auth_service = AuthService()
#     result = auth_service.verify_token(token)

#     if not result.get('valid'):
#         return jsonify({
#             'code': 401,
#             'message': result.get('message', 'token无效或已过期')
#         }), 401

@auth_bp.route('/login', methods=['GET', 'POST'])
def login():

    # 处理 SSO 回调
    code = request.args.get('code',None)
    
    auth = AuthService()
    result = auth.login(code)
    
    
    if not result.get('success'):
        if 'redirect_url' in result:
            return jsonify({
                "code": 302,
                "message": "需要重定向到SSO登录",
                "data": {
                    "redirect_url": result['redirect_url']
                }
            })
        return jsonify({
            "code": 401,
            "message": result.get('message', '登录失败')
        }), 401
    
    # 登录成功时将用户信息保存到 g.user
    g.user = result.get('user_info')
    
    return jsonify({
        "code": 200,
        "message": "登录成功",
        "data": {
            "token": result.get('token'),
            "user_info": result.get('user_info')
        }
    })

@auth_bp.route('/logout', methods=['POST'])
def logout():
    auth = AuthService()
    result = auth.logout()

    if result.get('success'):
        return jsonify({
            "code": 200,
            "message": "注销成功",
            "data": {
                "sso_logout_url": result['sso_logout_url']
            }
        })
    else:
        return jsonify({
            "code": 500,
            "message": "注销失败"
        }), 500

@auth_bp.route('/check-token', methods=['GET'])
def check_token():
    token = request.headers.get('Authorization')
    if not token:
        return jsonify({
            "code": 401,
            "message": "未提供token"
        }), 401
    
    auth = AuthService()
    result = auth.verify_token(token)
    
    if result.get('valid'):
        return jsonify({
            "code": 200,
            "message": "token有效",
            "data": result.get('user_info')
        })
    else:
        return jsonify({
            "code": 401,
            "message": "token无效或已过期"
        }), 401